var mysql = require('mysql2');
var config = require('../config/default.js')

var pool  = mysql.createPool({
  host     : config.database.HOST,
  user     : config.database.USERNAME,
  password : config.database.PASSWORD,
  database : config.database.DATABASE
});

let query = function( sql, values ) {

  return new Promise(( resolve, reject ) => {
    pool.getConnection(function(err, connection) {
      if (err) {
        reject( err )
      } else {
        connection.query(sql, values, ( err, rows) => {

          if ( err ) {
            reject( err )
          } else {
            resolve( rows )
          }
          connection.release()
        })
      }
    })
  })

}
//批量插入
let insertList = function( sql, values ) {

  return new Promise(( resolve, reject ) => {
    pool.getConnection(function(err, connection) {
      if (err) {
        reject( err )
      } else {
        connection.query(sql, [values], ( err, rows) => {

          if ( err ) {
            reject( err )
          } else {
            resolve( rows )
          }
          connection.release()
        })
      }
    })
  })

}
// 查找用户
let findUserData = function( name ) {
    let _sql = `select * from user where name="${name}"`
    return query( _sql )
}
//查找所有卡密
let findAllKami = function() {
    let _sql = `select * from kami`
    return query( _sql )
}
//查找卡密
let findByKami = function(kami) {
    let _sql = `select * from kami where kami="${kami}"`
    return query( _sql )
}
//激活卡密 1 代表active
let activeKami = function(id,out_time) {
  let _sql = "UPDATE `bb`.`kami` SET `active_time` = NOW(), `out_time` = ?, `last_time` = NOW(), `status` = 1  WHERE `id` = ?"
  var values=[];
  values.push(out_time,id);
  return query( _sql,values );
}
//按时间数量生成卡密
let newKami = function(values) {
  let _sql = "INSERT INTO kami(kami,validity,create_time) VALUES ?"
  return insertList( _sql,values)
}
module.exports={
    query,
    findUserData,
    findAllKami,
    findByKami,
    activeKami,
    newKami
}